using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using cframework;
using System.ComponentModel;
using Newtonsoft.Json;
using System.Drawing.Drawing2D;
namespace cframework
{
    [CreateAssetMenu(menuName = "cframework/FileSystemUtil_Local")]
    public class FileSystemUtil_Local : FileSystemUtil
    {
        [Essential]
        public string path;

        public override string GetDownloadUrl()
        {
            return System.IO.Path.GetFullPath(path).Replace("\\", "/");
        }

        public string GetLocalPath()
        {
            return System.IO.Path.GetFullPath(path).Replace("\\", "/");
        }

        public override bool Upload(string srcPath, string destPath)
        {
            if (System.IO.File.Exists(srcPath))
            {
                var destFilePath = GetLocalPath() + "/" + destPath;
                destFilePath = destFilePath.Replace("\\", "/");
                if (destFilePath.EndsWith("/"))
                {
                    destFilePath += System.IO.Path.GetFileName(srcPath);
                }

                try
                {
                    var dir = System.IO.Path.GetDirectoryName(destFilePath);
                    if (!System.IO.Directory.Exists(dir))
                    {
                        System.IO.Directory.CreateDirectory(dir);
                    }

                    System.IO.File.Copy(srcPath, destFilePath, true);
                }
                catch (System.Exception e)
                {
                    Debug.LogError($"copy file failed: {srcPath} => {destFilePath}");
                    throw e;
                }

            }
            else
            {
                string[] paths = System.IO.Directory.GetFiles(srcPath, "*", System.IO.SearchOption.AllDirectories);
                foreach (var p in paths)
                {
                    var q = p.Replace("\\", "/").Replace(srcPath + "/", "");
                    Upload(p, $"{destPath}/{q}");
                }
            }
            return true;
        }


        public override bool WriteAllText(string srcPath, string text)
        {
            System.IO.File.WriteAllText(GetLocalPath() + "/" + srcPath, text);
            return true;
        }

        public override string ReadAllText(string textPath)
        {
            if (System.IO.File.Exists(GetLocalPath() + "/" + textPath))
            {
                return System.IO.File.ReadAllText(GetLocalPath() + "/" + textPath);
            }
            return null;
        }
    }
}